package com.gxljc.bear.crawler.util;

import org.ansj.domain.Term;
import org.ansj.splitWord.analysis.ToAnalysis;
import org.apache.commons.lang.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class CrawlerCommonUtil {


    /**
     * @param lists    原始列表
     * @param pageNum
     * @param pageSize
     * @return 按照分页从List获取元素
     */
    public static <T> List<T> getSubList(List<T> lists, int pageNum, int pageSize) {
        int fromIndex = (pageNum - 1) * pageSize;
        int toIndex = fromIndex + pageSize;
        // 超出判断
        int size = lists.size();
        if (fromIndex >= size) {
            return new ArrayList<>();
        }
        return (List<T>) lists.subList(fromIndex, Math.min(size, toIndex));
    }

    /**
     * @param o
     * @return 验证Map, List, String 是否正常
     */
    @SuppressWarnings("rawtypes")
    public static boolean validateObject(Object o) {
        if (o instanceof Map) {
            return o != null && ((Map) o).size() > 0;
        }
        if (o instanceof List) {
            return o != null && ((List) o).size() > 0;
        }
        if (o instanceof String) {
            return o != null && ((String) o).length() > 0;
        }

        return false;
    }

    /**
     * @param sentence
     * @return 分词后去除空字符串
     */
    public static List<String> wordSegment(Object sentence) {
        List<Term> terms = ToAnalysis.parse(sentence.toString());
        List<String> termName = new ArrayList<String>();
        for (Term term : terms) {
            String str = term.getName();
            if (StringUtils.isNotBlank(str)) {
                termName.add(str);
            }
        }
        return termName;
    }



    /**
     * @param map
     */
    public static void outputMap(Map<String, Object> map) {
        System.out.println("**************");
        for (String s : map.keySet()) {
            System.out.println(s + "\t" + map.get(s));
        }
        System.out.println("**************");
    }
}
